﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StockHelper.Scripts.Comm
{
    class File
    {

        /// <summary>
        /// 保存文件 
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="data">byte数据</param>
        public static void Save(string path, byte[] data)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
            fs.Write(data, 0, data.Length);
            fs.Close();
        }
        /// <summary>
        /// 保存文件 移动端要注意使用unity路径
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="data">字符串数据</param>
        public static void Save(string path, string data)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
            byte[] array = System.Text.Encoding.UTF8.GetBytes(data);
            fs.Write(array, 0, array.Length);
            fs.Close();
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns>字符串数据</returns>
        public static string Take(string path)
        {
            if (!System.IO.File.Exists(path))
                return null;
            return System.IO.File.ReadAllText(path);
        }
        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns>二进制数据</returns>
        public static byte[] TakeFobyte(string path)
        {
            if (!System.IO.File.Exists(path))
                return null;
            return System.IO.File.ReadAllBytes(path);
        }

        public static bool Exists(string path)
        {
            return System.IO.File.Exists(path);
        }
        public static System.IO.Stream Create(string path)
        {
            return System.IO.File.Create(path);
        }
        public static void Delete(string path)
        {
            System.IO.File.Delete(path);
        }
        
        public static void Mkdir(string path)
        {
            if(!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }


        /// <summary>
        /// 字节转KB,MB...
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FormatBytes(long bytes)
        {
            string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" };
            int i = 0;
            double dblSByte = bytes;
            if (bytes > 1024)
                for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
                    dblSByte = bytes / 1024.0;
            return System.String.Format("{0:0.##}{1}", dblSByte, Suffix[i]);
        }

        /// <summary>
        /// 搜索所有文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="ex">后缀名</param>
        /// <returns>文件列表</returns>
        public static List<string> GetFiles(string path, string ex = "*", SearchOption option = SearchOption.TopDirectoryOnly)
        {
            List<string> list = new List<string>();
            DirectoryInfo Dir = new DirectoryInfo(path);
            FileInfo[] thefileInfo = Dir.GetFiles("*." + ex, option);
            foreach (FileInfo NextFile in thefileInfo)
            {
                list.Add(NextFile.FullName);
            }
            return list;
        }

        public static void Copy(string form , string to) {
            System.IO.File.Copy(form, to, true);
        }


        /// <summary>
        /// 计算Hash值
        /// </summary>
        public static string GetFileHash(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
            { return null; }
            using (System.IO.FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                //计算文件的MD5值
                System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                Byte[] buffer = calculator.ComputeHash(fs);
                calculator.Clear();
                //将字节数组转换成十六进制的字符串形式
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < buffer.Length; i++)
                {
                    stringBuilder.Append(buffer[i].ToString("x2"));
                }
                return stringBuilder.ToString();
            }
        }

        /// <summary>
        /// 搜索文件夹中的文件
        /// </summary>
        /// <param name="srcPath">路径</param>
        /// <param name="hasFile">是否搜索文件</param>
        /// <param name="hasDir">是否搜索文件夹</param>
        /// <returns></returns>
        public static FileSystemInfo[] GetDir(string srcPath, bool hasFile = true, bool hasDir = true)
        {
            DirectoryInfo dir = new DirectoryInfo(srcPath);
            List<FileSystemInfo> list = new List<FileSystemInfo>();
            foreach (FileSystemInfo i in dir.GetFileSystemInfos())
            {
                if (i is DirectoryInfo)
                {
                    if (hasDir)
                        list.Add(i);
                }
                else
                {
                    if (hasFile)
                        list.Add(i);
                }
            }
            return list.ToArray();
        }

        /// <summary>
        /// 删除指定文件目录下的所有文件
        /// </summary>
        /// <param name="fullPath">文件路径</param>
        public static void DeleteAllFile(string srcPath, string ex = null)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else if (ex == null || i.Extension == ex)
                    {
                        //如果 使用了 streamreader 在删除前 必须先关闭流 ，否则无法删除 sr.close();
                        Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (System.Exception e)
            {
                throw new System.Exception(e.ToString());
            }
        }

        public static string OpenFile(string filter = "所有文件(*.*)") {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = filter; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
                return fileDialog.FileName;//返回文件的完整路径
            else
                return null;
        }

    }
}
